const common = require('../../public.js')
const amap = require('../../libs/amap-wx')
const QQMapWX = require('../../libs/qqmap-wx-jssdk1.2/qqmap-wx-jssdk')
const app = getApp()

Page({
    data: {
        showRedPoint:false,
        selected: 0,
        tiaoBan: [],
        weather: [], //天气预报
        bannerList: [],
        currentIndex: 0,
        current: 0,
        controls: true,
        plays: true, //轮播图
        VenueList: [],
        pageSizes: 10,
        pageNum: 1,
        articleList: [],
        canLoad: true,
        isLoadingBusy: false,
        refreshing: false,
        typeList: [],
        active: 0,
        actives: 0,
        userInfo: {},
        laba: false,
        timeData: {},
        benefitListData: [], // 推荐商家列表
        swiperCurrent: 0,
        fList: [
            'http://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/coup/copu_chou.png',
            'http://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/coup/coup_rignt_index.png'
        ],
        storeText: '',
        fixs: 1,
        ll:'666',
        weatherUrl: 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/weather'
    },

    click_line(){
      wx.navigateTo({
        url: '/packageB/pages/Activity/actDes/index?id=100',
      })
    },
    click_v() {
        // wx.navigateTo({
        //   url: '/packageC/pages/Collarcoupons/Collarcoupons?accountId=1',
        // })
        // wx.navigateTo({
        //   url: '/pages/draw/index?drawId=217',
        // })
        // wx.navigateTo({
        //   url: '/packageB/pages/Activity/actDes/index?id=98',
        // })
        // wx.navigateTo({
        //   url: '/packageB/pages/DjM/index',
        // })
        // wx.navigateTo({
        //   url: '/packageB/pages/cultureCouponsM/receiveCouponM/index?managerId=121',
        // })

        // wx.navigateTo({
        //   url: '/pages/myNian/payCard/payCard?cardId=' + 51 + '&distributorId=' + 115,
        // })
    },

    swiperChanges(e) {
        var videoplay = wx.createVideoContext("video");
        videoplay.stop()
        this.setData({
            controls: true
        })
    },
    // 跳转会员卡
    go_card(e) {
        let item = e.currentTarget.dataset.item
        if (item.id == 16) {
            wx.navigateToMiniProgram({
                appId: 'wxaf35009675aa0b2a',
                path: '/pages/index/index?dchn=0j55kav', //跳转目标页面+携带参数 滴滴
                extraData: {
                    a: '123' //携带参数
                },
                envVersion: 'release',
                success(res) {
                    // 打开成功
                    // debugger
                }
            })
            return
        }
        if (item.redirectUrl) {
            if (item.id == 17) {
                wx.navigateTo({
                    url: '/pages/crowd/List/index'
                })
            } else {
                wx.navigateTo({
                    url: '/packageA/pages/Goods/details/index?id=' + item.redirectUrl
                })
            }

        } else {
            if (item.id == 17) {
                wx.navigateTo({
                    url: '/pages/crowd/List/index'
                })
            } else {
                wx.navigateTo({
                    url: item.redirectPath + '?managerId=' + item.managerId,
                })
            }
        }
    },
    // 首页第二轮播图
    adverList() {
        var that = this
        common.get('/advertisements/firstPageAds', {}, res => {
            if (res.status === 200) {
                that.setData({
                    tiaoBan: res.data
                })
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    click_typecategroy(e) {
        let {
            item
        } = e.currentTarget.dataset
        wx.navigateTo({
            url: '/pages/classification/classificationGoods/index?cid=' + item.cid,
        })
    },
    // 跳转精选好物
    goodsImgClick(e) {
        common.gotoGoodsPage(e.currentTarget.dataset.item)
    },
    // 跳转平台新闻
    gong_detailss(e) {

        //  wx.navigateTo({
        //     url: `/packageC/pages/choiceMealPerson/index?storeId=8637&TableId=7&deskName=22&seat=25`,
        // })


        // return;
        let {
            id,
            title
        } = e.currentTarget.dataset.item
        wx.navigateTo({
            url: '/packageB/pages/gongDetail/gongDetail?id=' + id + '&name=' + title,
        })
    },
    // 跳转景区
    toScenicArea(e) {
        let {
            id
        } = e.currentTarget.dataset
        wx.navigateTo({
            url: '/pages/ScenicArea/ScenicAreaMainPage/index?id=' + id + '&moduleType=' + 2,
        })
    },
    // 关闭声音
    click_labawu() {
        this.setData({
            laba: true
        })
    },

    // 打开声音
    click_labay() {
        this.setData({
            laba: false
        })
    },

    // 城市名片  /pages/draw/drawList/index
    click_chou() {
        wx.navigateTo({
            url: '/pages/draw/drawList/index',
        })
    },
    click_zhong() {
        wx.navigateTo({
            url: '/pages/crowd/List/index',
        })
    },
    // 跳转活动
    click_act() {
        wx.navigateTo({
            url: '/packageB/pages/Activity/Index/index',
        })
    },
    // 调准会员卡购买页
    click_cards() {
        wx.navigateTo({
            url: '/pages/myNian/payCard/payCard?cardId=7',
        })
    },
    // 跳转分类
    toCategoryList(e) {
        const id = e.currentTarget.dataset.item.id
        const name = e.currentTarget.dataset.item.name
        let url = null
        if (id == 6) {
            // 景区景点
            url = '/pages/ScenicArea/ScenicAreaList/index?type=1&id=' + id + '&name=' + name
        } else if (id == 17 || id == 23 || id == 24) {
            // 文化场馆
            url = '/pages/ScenicArea/ScenicAreaList/index?type=2&id=' + id + '&name=' + name
        } else {
            // 店铺
            url = '/pages/Type/TypeIndex/index?id=' + id + '&name=' + name
        }
        wx.navigateTo({
            url
        })
    },
    // 跳转搜索页面
    onClickSearch() {
        wx.navigateTo({
            url: '/packageB/pages/search/index'
        })
    },
    // 精选好物的接口
    getBenefitsPeopleStoreList(refresh = false) {
        if (this.data.isLoadingBusy) {
            return
        }
        this.setData({
            isLoadingBusy: true
        })
        const pageNum = refresh ? 1 : this.data.pageNum + 1
        const tempJson = {
            pageNum,
            xpoint: this.data.lon,
            ypoint: this.data.lat,
            cityName:this.data.cityName,
            regionName:this.data.regionName,
          
        }
        common.post('/item/getItemListByPoints', tempJson, (res) => {
            if (res.status === 200) {
                this.data.pageNum = pageNum
                if (!refresh) {
                    this.setData({
                        benefitListData: [...this.data.benefitListData, ...res.data]
                    })
                } else {
                    let moreData = true
                    if (res.data.length === 0) {
                        moreData = false
                    }
                    this.setData({
                        benefitListData: res.data,
                        isMore: moreData
                    })
                }
            } else {
                common.showRequestErrMsg(res)
            }
        }, () => {
            this.setData({
                isLoadingBusy: false
            })
        })
    },

    // 滚动监听
    scrollFn(e) {
        if (e.detail.scrollTop > 250) {
            this.setData({
                fixs: 0
            })
        } else {
            this.setData({
                fixs: 1
            })
        }
    },

    onLoad: function (options) {
        // const url = this.getAppLink()
        // console.log('返回的url：', url);
        // this.getAppLink()
       
        //获取胶囊位置
        let capsule = wx.getMenuButtonBoundingClientRect()
        this.setData({
            height: capsule.height,
            top: capsule.top,
        })
// https://www.520byte.com/api/app/public/get_fy_jump_url

        // wx.request({
        //     url: `https://www.api.520byte.com/api/app/public/customer_phone`,
        //     method: 'POST',
        //     header: {
        //         "Api-Version": "v308",
        //         'Token': "ea165a4a2566797917ee60aa53ef72288f9f7e5b12d0b64b674ab9e6995c63e3",
        //      },
        //     success(res) {
        //         console.log(res.data);
        //         //   that.setData({
        //         //     accessToken: res.data.access_token
        //         //   })
        //     }
        // })




        var windowHeight = wx.getSystemInfoSync().windowHeight
        var windowWidth = wx.getSystemInfoSync().windowWidth
        this.setData({
            scroll_height: windowHeight * 750 / windowWidth - 200
        })
        this.getBannerInfo()
        this.adverList()
        this.refresh()
        this.getGoodsType()
        this.gong_Gao()
        // this.needTokenAndMessageList();
   

    },

    onShow() {
        var that = this
        common.getLocalUserInfo(function (success, data) {
            if (success) {
                that.setData({
                    userInfo: data.user,
                    token: data.token
                }, function () {
                    this.read_message()
                })
            }
        })
    },
    // 统计用户未读消息
    read_message() {
        var that = this
        var tmp = {
            userId: this.data.userInfo.id,
            token: this.data.token
        }
        common.get('/alipush/getUserNotReadMessageCount', tmp, res => {
            if (res.status === 200) { } else {
                common.showRequestErrMsg(res)
            }

        })
    },

    duck_two(e) {
        var index = e.currentTarget.dataset.index
        if (index == 0) {
            wx.navigateTo({

                url: '/packageC/pages/Collarcoupons/Collarcoupons'
            })
        } else {
            wx.navigateTo({
                // url: '/pages/myNian/payCard/payCard?cardId=7&distributorId=5'
                url: '/packageC/pages/morePackCard/morePackCard?title=飞羊会员卡',
            })
        }
    },
    // 获取位置信息
    refresh() {
        var that = this
        // console.log( `${this.data.weatherUrl}/yuncai.png`)
        app.getLocation(
            (data) => {
                console.log('哈哈哈哈---',data);
                var adcode = data.ad_info.adcode
                this.data.lon = data.longitude
                this.data.lat = data.latitude
                this.data.cityName = data.regeocodeData.addressComponent.city
                this.data.regionName = data.regeocodeData.addressComponent.district
                this.data.region = data.regeocodeData.addressComponent.district // 地区
                this.setData({
                    city: data.regeocodeData.addressComponent.city
                }, () => {
                    this.tour()
                    this.Venue()
                    wx.request({
                        url: 'https://restapi.amap.com/v3/weather/weatherInfo',
                        data: {
                            'key': '7ccba778f92c5b0b3009c09e1a5a6905', //填入自己申请到的Key
                            'city': adcode,
                        },
                        header: {
                            'content-type': 'application/json'
                        },
                        success: function (res) {
                            // 判断显示天气对应的图标
                            // var weathe = res.data.lives[0].weather
                            // console.log(w)
                            // if (weathe.indexOf('多云') != -1 || weathe.indexOf('阴') != -1 || weathe.indexOf('风') != -1) {
                            //     res.data.lives[0].icon = `${this.data.weatherUrl}/yuncai.png`
                            // } else if (weathe == '晴') {
                            //     res.data.lives[0].icon = `${this.data.weatherUrl}/sunshine.png`
                            // } else if (weathe.indexOf('雪') != -1) {
                            //     res.data.lives[0].icon = `${this.data.weatherUrl}/weatherxue.png1`
                            // } else if (weathe.indexOf('雨') != -1 || weathe.indexOf('雹') != -1) {
                            //     res.data.lives[0].icon = 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/weather/weatheryu.png'
                            // } else if (weathe.indexOf('雾') != -1 || weathe.indexOf('霾') != -1) {
                            //     res.data.lives[0].icon = 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/weather/wumai.png'
                            // } else if (weathe.indexOf('尘') != -1) {
                            //     res.data.lives[0].icon = 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/weather/fucen.png'
                            // } else if (weathe.indexOf('雷') != -1) {
                            //     res.data.lives[0].icon = 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/weather/leidian.png'
                            // }
                            that.setData({
                                weather: res.data.lives
                            }, () => {

                            })
                        }
                    })
                    this.getBenefitsPeopleStoreList(true)
                })
            })
    },

    // weatherFn(){
    //   let wetherList = ['多云','晴','雪','阴','风','雨','雹','雾','霾','尘','雷']
    // },

    // 必玩景区接口
    tour() {
        var that = this
        let tempJson = {
            storeTypeId: 6,
            regionName: '',
            cityName: '枣庄市',
            pageNum: 1,
            pageSize: 10,
            xpoint: this.data.lon,
            ypoint: this.data.lat,
            distance: '',
            recentIncome: '',
            commentRate: '',
        }
        common.post('/store/getSearchStoreListByStoreTypeId', tempJson, function (res) {
            if (res.status === 200) {
                that.setData({
                    tourList: res.data
                })
            }
        })
    },
    // 附近场馆接口
    Venue() {
        var that = this
        let tempJson = {
            storeTypeId: 23,
            cityName: '枣庄市',
            pageNum: 1,
            pageSize: 9,
            xpoint: this.data.lon,
            ypoint: this.data.lat,
            distance: '',
            recentIncome: '',
            commentRate: '',
            Index: 0
        }
        common.post('/store/getSearchStoreListByStoreTypeId', tempJson, function (res) {
            if (res.status === 200) {
                //  res.data = res.data.splice(1)
                for (var i = 0; i < res.data.length; i++) {
                    res.data[i].distance = parseFloat(res.data[i].distance / 1000).toFixed(1)
                }
                // 第一步 先设置数组前三个比较
                var min = res.data[0].distance
                for (var i = 1; i < 2; i++) {
                    var cur = res.data[i].distance
                    // 小于等于
                    if (cur < min) {
                        min = cur
                        res.data[i]['aa'] = true
                        var obj = {}
                        obj = res.data[0]
                        res.data[0] = res.data[i]
                        res.data[i] = obj
                    } else {
                        res.data[0]['aa'] = true
                    }
                    that.setData({
                        VenueList: res.data
                    })

                }

            }
        })
    },
    //  公告新闻列表
    gong_Gao() {
        var that = this
        var tempJson = {
            regionId: 1,
            pageSize: 10,
            pageNum: 1
        }
        common.getJson('/wlplatfrom/selectAnnouncementList', tempJson, res => {
            if (res.status === 200) {
                for (var i = 0; i < res.data.length; i++) {
                    // res.data.itemDesc.replace(/\<img/gi, '<img class="rich-img" ') : ''
                    res.data[i].description = res.data[i].description.replace(/\<p>/gi, ' ')
                }
                that.setData({
                    gong: res.data
                })
            }
        })
    },
    //获取首页banner图数据
    getBannerInfo() {
        var that = this
        common.getJson('/wlplatfrom/xcx/selectRegionContentListForXcx', {
            "regionId": 1
        }, res => {
            if (res.status === 200) {
                this.setData({
                    bannerList: res.data
                })
            }
        })
    },
    //获取商品分类
    getGoodsType() {
        const tempJson = {
            type: 15
        }
        common.post('/store/getStoreTypeListForAppByPara', tempJson, res => {
            const list = this.chunkArr(res.data, 10)
            this.setData({
                banner: list
            })
        })
    },
    chunkArr(arr, size) {
        //判断如果不是数组(就没有length)，或者size没有传值，size小于1，就返回空数组
        if (!arr.length || !size || size < 1) return []
        let [start, end, result] = [null, null, []]
        for (let i = 0; i < Math.ceil(arr.length / size); i++) {
            start = i * size
            end = start + size
            result.push(arr.slice(start, end))
        }
        return result

    },
    /* 这里实现控制中间凸显图片的样式 */
    handleChange: function (e) {
        if (this.data.current == 0 && this.data.currentIndex > 1) { //卡死时，重置current为正确索引
            this.setData({
                current: this.data.currentIndex
            });
        } else { //正常轮转时，记录正确页码索引
            this.setData({
                currentIndex: e.detail.current
            });
        }
    },
    // 附近场馆计算最短距离
    handleChanges(e) {
        var that = this
        // 三位比较大小
        var Index = e.detail.current //轮播图的第一位
        that.setData({
            Index
        }, () => {
            var arr = that.data.VenueList.slice(that.data.Index, that.data.Index + 3)
            if (arr.length == 0) {
                arr.push(that.data.VenueList[0], that.data.VenueList[1], that.data.VenueList[2])
            } else if (arr.length == 1) {
                arr.push(that.data.VenueList[0], that.data.VenueList[1],)
            } else if (arr.length == 2) {
                arr.push(that.data.VenueList[0])
            }
            var min = arr[0].distance
            var id = 0
            var smallIndex = 0 //小数组里面的下标
            for (var j = 0; j < arr.length; j++) {
                var cur = parseFloat(arr[j].distance)
                if (cur <= min) {
                    min = cur
                    smallIndex = j
                    id = arr[j].id

                }
            }
            var bigIndex = 0
            for (var i = 0; i < that.data.VenueList.length; i++) {
                if (id == that.data.VenueList[i].id) {
                    that.data.VenueList[i]['aa'] = true
                    bigIndex = i
                    var obj = {}
                    obj = that.data.VenueList[i]
                    that.data.VenueList[i] = that.data.VenueList[Index]
                    that.data.VenueList[Index] = obj
                } else {
                    that.data.VenueList[i]['aa'] = false
                }
            }
            that.setData({
                VenueList: that.data.VenueList
            }, () => { })

        })
    },
    loadMore() {
        this.getBenefitsPeopleStoreList(false)
    },
    onPullDownRefresh: function () {
        this.getBenefitsPeopleStoreList(false)
    },

    onShareAppMessage: function () {
        return {
            title: '飞羊精选',
            path: 'pages/index/index',
            imageUrl: 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/xfj/share.jpg',
            success: (res) => { },
            fail: (res) => {
                // 分享失败
            }
        }
    },
    onShareTimeline() {
        return {
            title: '飞羊精选',
            path: 'pages/index/index',
            imageUrl: 'https://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/xfj/share.jpg',
            success: (res) => { },
            fail: (res) => {
                // 分享失败
            }
        }
    },

    needTokenAndMessageList(){
        
        var that = this
    common.getLocalUserInfo(function (success, data) {
      if (success) {
        that.setData({
          userInfo: data.user,
          token: data.token
        }, function () {
          that.mess_fn();
          // wx.hideTabBarRedDot({
          //   index: 3,
          // })
        })
      } else {
        that.setData({
          userInfo: null,
          token: '',
        })
      }
    })
    },

    mess_fn() {
        var that = this
        var tmp = {
          userId: that.data.userInfo.id,
          messageType: 10,
          token: that.data.token,
          pageNum: that.data.pageNum,
          pageSize: 10
        }
        common.get('/userMessage/getUserMessage', tmp, res => {
          if (res.status === 200) {
              var list = res.data;
          
         
       
            that.setData({
              showRedPoint: list.length>0?true:false,
       
              
            },function(){
                // that.setData({
                //     nianList: list<10,
                    
                //   })
            })
          } else {
            common.showRequestErrMsg(res)
          }
        })
      },

})